package com.example.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.domain.dh.OAMJEntity;
import com.example.service.DHService;
import com.example.utils.config.CommonConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * 大华 接口
 * @author user
 *
 */
@Slf4j
@RestController
@RequestMapping("/dh")
public class DHController {

	@Autowired
    private DHService dhService;
	
	
	@RequestMapping("/getLoginToken")
    public String getLoginToken(){
        return dhService.queryLoginToken();
    }
	
	/**
	 * 获取传到大华的数据
	 * 
	 *  POST:   http://ip:port/CardSolution/card/person?userId=1&userName=system 
	        参数名称	 
			paperType	 	  证件类型：身份证、军官证、学生证、驾驶证、护照、港澳通行证
			paperNumber	 	  人员证件号
			name	     	  姓名
			code	          人员编号
			deptId	          所属部门id，部门查询接口返回的id
			sex	              性别 ：男、女           中文
			birthday	      生日 2000-01-01
			phone	          电话
			status	          人员状态：在职，离职       中文
			fingerCode	      指纹1，大华指纹读头读出来的指纹数据
			secfingerCode	  指纹2
			personIdentityId  身份ID，身份查询接口返回的ID
			
			{
			    "paperNumber":"320723199504243611",
			    "name":"张三",
			    "code":"1024",
			    "deptId":2,
			    "sex":"男",
			    "birthday":"2000-08-13",
			    "phone":"15961791569",
			    "status":"在职",
			    "paperType":"身份证"
			}
			
	 * @param loginid  用户id
	 * @param map 
	 * @return
	 */
	@RequestMapping("/queryMJData")
    public String get2DHData(String requestId,String tableName){
		log.info("门禁流程过程传递参数,requestId:{},tableName:{}", requestId, tableName);
		List<OAMJEntity> mjList = dhService.getMJData(requestId);
		log.info("从流程中获取到的数据:{}", mjList);
		if(mjList!=null && mjList.size()>0) {
			OAMJEntity oamjEntity = mjList.get(0);
			String str = dhService.queryDHPersonByLoginId(oamjEntity.getLoginId());
			if("0".equals(str)) {// 新增
				StringBuffer sb = new StringBuffer();
				sb.append("{");
				sb.append("\"paperType\":\""+"身份证"+"\",");
				sb.append("\"paperNumber\":\""+oamjEntity.getCertificatenum()+"\",");
				sb.append("\"name\":\""+oamjEntity.getLastName()+"\",");
				sb.append("\"code\":\""+oamjEntity.getLoginId()+"\",");
				sb.append("\"deptId\":113,");// 113新人
				sb.append("\"sex\":\""+oamjEntity.getSex()+"\",");
				if(oamjEntity.getBirthday() != null && !"".equals(oamjEntity.getBirthday())) {
					sb.append("\"birthday\":\""+oamjEntity.getBirthday()+"\",");
				}
				sb.append("\"phone\":\""+oamjEntity.getMobile()+"\",");
				sb.append("\"status\":\""+oamjEntity.getStatus()+"\",");
				sb.append("\"personIdentityId\":1");// 1 普通员工
				sb.append("}");
				log.info("即将新增到大华系统的用户信息:{}",sb.toString());
				dhService.addDHPerson(sb.toString()); // 调用大华接口新增人员信息
			}else { // 存在用户，不处理
				log.info("大华已经存在对应用户,不进行其他操作");
			}
		}
		return "success";
    }
	
	@RequestMapping("/test")
    public String test(String loginId){
		dhService.queryDHPersonByLoginId(loginId);
		return "success";
    }
	
	@RequestMapping("/getCarToken")
    public String getCarToken(){
        return dhService.queryCarToken();
    }
	
	/**
	 * 测试   http://localhost:9000/dh/queryDataByCarid?carid=19909&billid=&img=
	 * @param params
	 * @return
	 */
	@RequestMapping("/queryDataByCarid")
    public String queryDataByCarid(@RequestBody String params){
		String carid = "";
		String billid = "";
		String img = "";
		
		System.out.println("参数："+params);
		if(params.contains("&")) {
			for (String p : params.split("&")) {
				System.out.println("=============="+p);
				if(p.contains("img=")) {
					img = p.replaceAll("img=", "");
				}
				if(p.contains("carid=")) {
					carid = p.replaceAll("carid=", "");
				}
				if(p.contains("billid=")) {
					billid = p.replaceAll("billid=", "");
				}
			}
		} else {
			JSONObject pObj = JSONObject.parseObject(params);
			carid = pObj.get("carid").toString();
			billid = pObj.get("billid").toString();
			img = pObj.get("img").toString();
		}
		log.info("输入的车牌号：{}", carid.toUpperCase());
		log.info("表单id：{},根据表单id查询图片", billid);
		log.info("图片：{}", img);
		img = img.replaceAll("%2F", "/").replaceAll("%2B", "+").replaceAll("%3D", "=");
		log.info("图片转换后：{}", img);
		if(StringUtils.isBlank(billid)) {
			return dhService.queryDataByCarid(carid.toUpperCase());
		} else {
			String profile = CommonConfig.getProfile();
			String imgUrl = convertBase64ToImage(img, profile, billid);
			System.out.println("生成图片的url:"+imgUrl);
			String retMsg = dhService.ocrImgData(imgUrl);
			System.out.println("result====:"+retMsg);
			return retMsg;
		}
    }
	
	public static String convertBase64ToImage(String base64Code, String profile, String billid){
        BufferedImage image = null;
        byte[] imageByte = null;
        try {
            imageByte = DatatypeConverter.parseBase64Binary(base64Code);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(new ByteArrayInputStream(imageByte));
            bis.close();
            File outputfile = new File(profile+"\\"+billid+".jpg");
            ImageIO.write(image, "jpg", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:9000/api/excel/"+billid+".jpg";
    }
	
}

